package com.xiaotu.spider;

import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.xiaotu.common.model.SpiderLogModel;
import com.xiaotu.common.util.SepratorUtil;
import com.xiaotu.common.util.SpringContextHolder;
import com.xiaotu.common.util.UUIDUtils;
import com.xiaotu.spider.monitor.SpiderMonitorThread;

/**
 * @类名 SpiderTask
 * @日期 2017年2月10日
 * @作者 高海军
 * @功能 整个爬虫任务入口
 */
public class SpiderRunner
{

    private static final Logger LOGGER = LoggerFactory.getLogger(SpiderRunner.class);

    /**
     * 爬虫任务入口
     *
     * @param args 线程数、pageprocessor名称（任务名称）、pipeline名称、数据源缓存key、sleeptime
     */
    public static void main(String[] args)
    {
        final SpiderLogModel spiderLog = new SpiderLogModel();
        try
        {

            SpringContextHolder.setApplicationContext();
            spiderLog.setSeriesNo(UUIDUtils.getStringUUID());
            spiderLog.setStartTime(System.currentTimeMillis());

            if (args == null || args.length < 1)
                throw new RuntimeException("params is empty");
            Map<String, Object> map = new HashMap<String, Object>();
            for (String para : args)
            {
                String[] paras = para.split(SepratorUtil.SEP_EQUAL);
                if (paras.length != 2)
                    throw new RuntimeException("params is error");
                map.put(paras[0], paras[1]);
            }

            SpiderFactory spiderFactory = SpringContextHolder.getBean("spiderFactory", SpiderFactory.class);
            spiderFactory.runSpider(map, spiderLog);
        }
        catch (Exception e)
        {
            LOGGER.error("[{}] Task ERROR", spiderLog.getJobType(), e);
            spiderLog.setSpiderStatus(SpiderMonitorThread.STATUS_STOPPED);
            spiderLog.setException(e.getClass().getSimpleName());
            spiderLog.setMessage(e.getMessage());
            SpringContextHolder.getBean("spiderMonitorThread", SpiderMonitorThread.class).refreshTaskLog(spiderLog);
        }
    }

}
